import trackService from '@/services/track-service';
import {
  DeleteOutlined,
  QuestionCircleOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import {
  Button,
  Card,
  Input,
  Pagination,
  Popconfirm,
  Space,
  Spin,
  Table,
  Tag,
  Tooltip,
  Typography,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import './index.less';

const { Title, Text } = Typography;

interface ClusterItem {
  cluster_id: string;
  user_identifier: string;
  question_pattern: string;
  question_count: number;
  create_time: number;
  update_time: number;
}

const ClusterListPage = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ClusterItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchParams, setSearchParams] = useState({
    user_identifier: '',
    page: 1,
    page_size: 10,
  });

  // 获取聚类列表数据
  const fetchClusterList = async () => {
    try {
      setLoading(true);
      const res = await trackService.cluster_list(searchParams);
      if (res.data.code === 0) {
        setData(res.data.data.list);
        setPagination({
          ...pagination,
          total: res.data.data.total,
          current: searchParams.page,
        });
      } else {
        message.error(res.data.message || '获取数据失败');
      }
    } catch (error) {
      message.error('请求失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchClusterList();
  }, [searchParams]);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchParams({
      ...searchParams,
      user_identifier: value,
      page: 1,
    });
  };

  // 处理分页变化
  const handlePaginationChange = (page: number, pageSize?: number) => {
    setSearchParams({
      ...searchParams,
      page,
      page_size: pageSize || pagination.pageSize,
    });
  };

  // 删除聚类
  const handleDelete = async (clusterId: string) => {
    try {
      const res = await trackService.cluster_delete({ cluster_id: clusterId });
      if (res.data.code === 0) {
        message.success('删除成功');
        fetchClusterList();
      } else {
        message.error(res.data.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败: ' + error.message);
    }
  };

  // 表格列配置
  const columns = [
    {
      title: '用户标识',
      dataIndex: 'user_identifier',
      key: 'user_identifier',
      width: 150,
      render: (text: string) => (
        <Tooltip title={text}>
          <Text ellipsis style={{ width: 120 }}>
            {text || '匿名用户'}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '对话id',
      dataIndex: 'conversation_id',
      key: 'conversation_id',
      render: (text: string) => (
        <Tooltip title={text}>
          <Text ellipsis style={{ maxWidth: 300 }}>
            {text}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '问题模式',
      dataIndex: 'question_pattern',
      key: 'question_pattern',
      render: (text: string) => (
        <Tooltip title={text}>
          <Text ellipsis style={{ maxWidth: 300 }}>
            {text}
          </Text>
        </Tooltip>
      ),
    },
    {
      title: '问题数量',
      dataIndex: 'question_count',
      key: 'question_count',
      width: 100,
      render: (count: number) => (
        <Tag color={count > 5 ? 'volcano' : count > 1 ? 'orange' : 'green'}>
          {count}
        </Tag>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      width: 180,
      render: (timestamp: number) => (
        <Text type="secondary">{new Date(timestamp).toLocaleString()}</Text>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: ClusterItem) => (
        <Popconfirm
          title="确定要删除这个聚类吗？"
          icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
          onConfirm={() => handleDelete(record.cluster_id)}
        >
          <Button type="text" danger icon={<DeleteOutlined />} size="small" />
        </Popconfirm>
      ),
    },
  ];

  return (
    <div className="cluster-list-page">
      <Card bordered={false}>
        <div className="cluster-header">
          <Title level={4} style={{ marginBottom: 0 }}>
            聚类结果列表
          </Title>
          <Space>
            <Input.Search
              placeholder="搜索用户标识"
              allowClear
              enterButton={<SearchOutlined />}
              onSearch={handleSearch}
              style={{ width: 250 }}
            />
            <Button
              icon={<ReloadOutlined />}
              onClick={() => fetchClusterList()}
            >
              刷新
            </Button>
          </Space>
        </div>

        <div className="cluster-table">
          <Spin spinning={loading}>
            <Table
              columns={columns}
              dataSource={data}
              rowKey="cluster_id"
              pagination={false}
              scroll={{ x: 'max-content' }}
              bordered
            />

            <div className="cluster-pagination">
              <Pagination
                current={pagination.current}
                pageSize={pagination.pageSize}
                total={pagination.total}
                onChange={handlePaginationChange}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `共 ${total} 条聚类结果`}
              />
            </div>
          </Spin>
        </div>
      </Card>
    </div>
  );
};

export default ClusterListPage;
